package com.hxrd.androidprint;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.hxrd.androidprint.DBUtils.DBUtils;

import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class LoginActivity extends AppCompatActivity {

    EditText loginName;
    EditText loginPsw;
    ImageView rememberPsw;
    Button btnLogin;
    Handler handler;

    //获取登录名和密码
    String name;
    String password;

    //获取用户姓名
    String userName;
    String userNamePrint;

    //登录的弹出框
    private Dialog dialog;

    //重新启动APP获取登录名和密码
    SharedPreferences getShared;


    String paramName = "Login_Name=";
    String paramPsw = "&User_PW=";

    //定义用户编码以便修改个人密码
    String userCode;

    //是否修改密码的状态
    Boolean isChangePwd;

    //登录弹出框
    private ProgressDialog progressdialog;

    String[] temp;

    String failMsg;

    Button btnFinish;


    private String urlIp;

    private ImageView settingImage;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);//取消标题栏
        //取消状态栏
        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_login);

        initView();

        getShared = getSharedPreferences("remember_password", MODE_PRIVATE);
        boolean isRemember = getShared.getBoolean("is_remember_psw", false);//false为默认值
        isChangePwd=getShared.getBoolean("is_change_pwd",false);
        //如果修改密码的状态为真
        if(isChangePwd==true){

            SharedPreferences sharedPreferences = getSharedPreferences("remember_password", MODE_PRIVATE);
            SharedPreferences.Editor editor = sharedPreferences.edit();
            editor.remove("password");
            editor.commit();
            //rememberPsw.setSelected(false);
        }

        //如果是否记住密码为true，则获得用户名和密码并显示在输入框内，并把密码选择框设置为选择状态
        if (isRemember == true) {
            String savePwd = getShared.getString("password", "");
            String saveName = getShared.getString("name", "");
            loginName.setText(saveName);
            loginPsw.setText(savePwd);
            rememberPsw.setSelected(true);
        }else {
            String saveName = getShared.getString("name", "");
            loginName.setText(saveName);
            rememberPsw.setSelected(false);
        }

        urlIp= DBUtils.queryUrl(LoginActivity.this);
        if(urlIp==null){
            DBUtils.insertUrl(LoginActivity.this,UrlPath.URL_IP);

            urlIp= DBUtils.queryUrl(LoginActivity.this);
        }


        initEvent();

    }


    @Override
    protected void onRestart() {
        super.onRestart();
        urlIp=DBUtils.queryUrl(LoginActivity.this);
    }

    private void initView() {
        rememberPsw = (ImageView) findViewById(R.id.remember_psw_image);
        loginName = (EditText) findViewById(R.id.edit_login_name);
        loginPsw = (EditText) findViewById(R.id.edit_login_psw);
        btnLogin = (Button) findViewById(R.id.btn_login);
        btnFinish = (Button) findViewById(R.id.btn_login_finish);
        settingImage=(ImageView) findViewById(R.id.setting_image);
    }

    private void initEvent() {

        settingImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(LoginActivity.this,UpdateUrlActivity.class);
                intent.putExtra("urlIp",urlIp);
                startActivity(intent);
            }
        });

        btnFinish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });


        btnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {


                //获取登录名和密码
                name = loginName.getText().toString();
                password = loginPsw.getText().toString();

                // startActivity(new Intent(LoginActivity.this, MainActivity.class));
                //dialog = new Dialog(LoginActivity.this, R.style.DialogStyle);

                progressdialog =ProgressDialog.show(LoginActivity.this, "请等待...", "正在为您登陆...");
                progressdialog.setCancelable(true);// 设置是否可以通过点击Back键取消

                if (!TextUtils.isEmpty(name.toString().trim()) &&
                        !TextUtils.isEmpty(password.toString().trim())) {
                    initUrl();

                } else {
                    progressdialog.dismiss();
                    Toast.makeText(LoginActivity.this, "请输入用户名或者密码", Toast.LENGTH_SHORT).show();
                }


            }
        });


        rememberPsw.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                rememberPsw.setSelected(!rememberPsw.isSelected());

                if (rememberPsw.isSelected()) {
                    //初始化SharedPreferences
                    SharedPreferences sharedPreferences = getSharedPreferences("remember_password", MODE_PRIVATE);
                    SharedPreferences.Editor editor = sharedPreferences.edit();
                    //把账号密码存入SharedPreferences
                    editor.putString("name", loginName.getText().toString());
                    editor.putString("password", loginPsw.getText().toString());
                    editor.putBoolean("is_remember_psw", true);
                    editor.putBoolean("is_change_pwd",false);
                    editor.commit();
                } else {
                    //初始化SharedPreferences
                    SharedPreferences sharedPreferences = getSharedPreferences("remember_password", MODE_PRIVATE);
                    SharedPreferences.Editor editor = sharedPreferences.edit();
                    //把存储的密码给清除掉
                    editor.remove("password");
                    editor.putBoolean("is_remember_psw", false);
                    editor.commit();
                }
            }
        });

        initData();

    }



    private void initData() {
        //处理返回来的数据
        handler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message message) {

                if (message.what == 1) {

                    progressdialog.dismiss();

                    final Intent intent = new Intent(LoginActivity.this, WarehouseSendGoodsActivity.class);
                    new Timer().schedule(new TimerTask() {
                        @Override
                        public void run() {
                            //这里是1S后执行的代码
                            intent.putExtra("name",loginName.getText().toString().trim());
                            intent.putExtra("urlIp",urlIp);
                            startActivity(intent);
                            finish();
                        }
                    }, 1 * 1000);



                    Toast.makeText(LoginActivity.this, "登录成功", Toast.LENGTH_SHORT).show();

                    // 登录成功，把用户名，密码和记住密码状态存储起来
                    SharedPreferences sharedPreferences = getSharedPreferences("remember_password", MODE_PRIVATE);
                    SharedPreferences.Editor editor = sharedPreferences.edit();
                    //把账号密码存入SharedPreferences
                    editor.putString("name", loginName.getText().toString());
                    editor.putString("password", loginPsw.getText().toString());
                    editor.putBoolean("is_remember_psw", rememberPsw.isSelected());
                    editor.putBoolean("is_change_pwd",false);
                    editor.commit();

                    new Timer().schedule(new TimerTask() {
                        @Override
                        public void run() {
                            //这里是1S后执行的代码
                            finish();
                        }
                    }, 1 * 1000);


                } else if (message.what == 2) {
//                    dialog.dismiss();
                    progressdialog.dismiss();

                    Toast.makeText(LoginActivity.this, "您输入的用户名或密码有误", Toast.LENGTH_SHORT).show();
                }
                if (message.what == 3) {
                    //dialog.dismiss();
                    progressdialog.dismiss();

                    Toast.makeText(LoginActivity.this, "请求网络失败,请检查您的网络！", Toast.LENGTH_SHORT).show();
                }
                return false;
            }
        });

    }

    //扫描架码的网络请求
    private void initUrl() {
        OkHttpClient client=new OkHttpClient();
        Request request=new Request.Builder().url(urlIp+UrlPath.LOGIN_URL+ paramName + name
                + paramPsw + password).build();
        Call call=client.newCall(request);
        call.enqueue(new Callback() {

            @Override
            public void onFailure(Call call, IOException e) {
                handler.sendEmptyMessage(3);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result=response.body().string();
                if(result.contains("true")){
                    handler.sendEmptyMessage(1);
                }
                if(result.contains("false")){
                    handler.sendEmptyMessage(2);
                }
            }
        });
    }



}
